from rest_framework.views import exception_handler
from rest_framework.response import Response
from utils.common_logger import logger


def common_exception_handler(exc, context):
    # 记录日志
    request = context.get('request')
    view_name = context.get('view').__class__.__name__
    ip = request.META.get('REMOTE_ADDR')
    path = request.get_full_path()
    method = request.method
    user_id = request.user.id or '【匿名用户】'
    logger.error(
        f'操作出错：{str(exc)},ip地址为：{ip},请求方式是：{method}，请求地址是：{path}，用户为：{user_id}，视图为:{str(view_name)}')
    response = exception_handler(exc, context)
    print(exc)
    if response:
        if isinstance(response.data, list):
            err = response.data[0]
        elif isinstance(response.data, dict):
            err = response.data
        else:
            err = '系统错误，请联系系统管理员'
        response = Response({'code': 999, 'msg': err})
    else:
        print(1)
        if isinstance(exc, ZeroDivisionError):
            code = 950
            err = f'{view_name}视图出错了，错误信息：不能除以0'
        elif isinstance(exc, TypeError):
            code = 951
            err = f'{view_name}视图出错了，错误信息：类型错误，不同类型不能操作'
        elif isinstance(exc, KeyError):
            code = 952
            err = f'{view_name}视图出错了，错误信息：字典键错误，不存在键'
        elif isinstance(exc, ValueError):
            code = 953
            err = f'{view_name}视图出错了，错误信息：值错误，类型不对'
        elif isinstance(exc, NameError):
            code = 954
            err = f'{view_name}视图出错了，错误信息：变量名错误，变量未被定义'
        elif isinstance(exc, IndexError):
            code = 955
            err = f'{view_name}视图出错了，错误信息：索引错误，超出范围'
        else:
            code = 956
            err = f'{str(exc)}'
        response = Response({'code': code, 'msg': err})
    return response